import React, { useState, useEffect, useMemo } from 'react';
import plcService from '../services/plcService';
import usePLCOperations from '../hooks/usePLCOperations';
import PLCVariableRow from './PLCVariableRow';
import { createDefaultVariable, isBooleanType } from '../utils/plcUtils';
import './PLCPanel.css';

export default function PLCGroupPanel() {
  const [isConnected, setIsConnected] = useState(false);
  const [groups, setGroups] = useState([]);
  const [groupData, setGroupData] = useState({});
  const [activeGroup, setActiveGroup] = useState(null);
  const [groupFiles, setGroupFiles] = useState([]); // 新增：用于存储分组文件列表
  const [groupVariables, setGroupVariables] = useState({}); // 新增：用于存储每个分组的变量列表
  const [groupSearchTerm, setGroupSearchTerm] = useState(''); // 新增：分组搜索状态

  // 使用 useMemo 优化搜索过滤
  const filteredGroups = useMemo(() => {
    if (!groupSearchTerm) return groups;
    return groups.filter(group => 
      group.name.toLowerCase().includes(groupSearchTerm.toLowerCase()) ||
      group.id.toLowerCase().includes(groupSearchTerm.toLowerCase()) ||
      (group.description && group.description.toLowerCase().includes(groupSearchTerm.toLowerCase()))
    );
  }, [groups, groupSearchTerm]);

  // 使用共享的PLC操作Hook
  const { loading, error, handleRead, handleWrite, showNotification, setLoading, setError } = usePLCOperations();

  // 检查变量是否为布尔类型 - 新增函数
  const isBooleanTypeLocal = (address) => {
    return isBooleanType(address);
  };

  // 初始化PLC分组面板
  useEffect(() => {
    const initPLCGroupPanel = async () => {
      try {
        // 检查PLC连接状态
        const status = await plcService.getStatus();
        setIsConnected(status.connected);
        
        // 检查本地存储中是否有已加载的分组配置
        const storedGroups = localStorage.getItem('plcGroups');
        if (storedGroups) {
          try {
            const parsedGroups = JSON.parse(storedGroups);
            setGroups(parsedGroups);
            // 初始化每个分组的变量列表
            const initialVariables = {};
            parsedGroups.forEach(group => {
              initialVariables[group.id] = group.variables.map(v => ({ 
                ...v, 
                value: '' 
              }));
            });
            setGroupVariables(initialVariables);
            // 如果有分组，默认选择第一个
            if (parsedGroups.length > 0) {
              setActiveGroup(parsedGroups[0].id);
            }
            console.log('📥 从本地存储加载分组配置:', parsedGroups);
          } catch (err) {
            console.error('❌ 解析本地存储的分组配置失败:', err);
            localStorage.removeItem('plcGroups');
          }
        }
        
        // 获取分组文件列表
        await loadGroupFiles();
      } catch (err) {
        console.error('初始化PLC分组面板失败:', err);
        setError('初始化PLC分组面板失败: ' + err.message);
      }
    };

    initPLCGroupPanel();
    
    // 每5秒检查一次连接状态
    const interval = setInterval(async () => {
      try {
        const status = await plcService.getStatus();
        setIsConnected(status.connected);
        setError(null);
      } catch (err) {
        console.error('检查PLC状态失败:', err);
        setError('检查PLC状态失败: ' + err.message);
      }
    }, 5000);
    
    return () => clearInterval(interval);
  }, [setError]);

  // 连接PLC
  const handleConnect = async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await plcService.connect();
      setIsConnected(result.connected);
      if (result.connected) {
        showNotification('✅ PLC连接成功', 'success');
      } else {
        alert('❌ PLC连接失败');
      }
    } catch (err) {
      const errorMessage = err.message || '连接PLC时发生未知错误';
      setError('连接PLC失败: ' + errorMessage);
      alert('❌ 连接PLC时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 断开PLC连接
  const handleDisconnect = async () => {
    setLoading(true);
    setError(null);
    try {
      await plcService.disconnect();
      setIsConnected(false);
      setGroupData({});
      showNotification('🔌 PLC连接已断开', 'info');
    } catch (err) {
      const errorMessage = err.message || '断开PLC连接时发生未知错误';
      setError('断开PLC连接失败: ' + errorMessage);
      alert('❌ 断开PLC连接时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 获取分组文件列表 - 新增方法
  const loadGroupFiles = async () => {
    setLoading(true);
    setError(null);
    try {
      console.log('🔄 正在获取分组文件列表...');
      const result = await plcService.getGroupFiles();
      console.log('📥 获取分组文件列表结果:', result);
      if (result.success) {
        console.log('📁 分组文件数量:', result.files.length);
        setGroupFiles(result.files);
        
        // 同时更新groups状态，确保UI能显示所有分组文件
        // 从文件名中提取分组ID和名称
        const groupList = result.files.map(file => {
          // 移除.json扩展名
          const fileName = file.replace('.json', '');
          // 使用文件名作为ID和名称
          return {
            id: fileName,
            name: fileName,
            description: `分组文件: ${file}`,
            variables: []
          };
        });
        
        setGroups(groupList);
        showNotification(`✅ 获取到 ${result.files.length} 个分组配置文件`, 'success');
      } else {
        const errorMessage = result.error || result.message || '未知错误';
        setError('获取分组文件列表失败: ' + errorMessage);
        alert('❌ 获取分组文件列表失败: ' + errorMessage);
      }
    } catch (err) {
      const errorMessage = err.message || '获取分组文件列表时发生未知错误';
      setError('获取分组文件列表失败: ' + errorMessage);
      alert('❌ 获取分组文件列表时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 保存分组配置到本地存储
  const saveGroupsToLocalStorage = (groupsToSave) => {
    try {
      localStorage.setItem('plcGroups', JSON.stringify(groupsToSave));
      console.log('💾 分组配置已保存到本地存储');
    } catch (err) {
      console.error('❌ 保存分组配置到本地存储失败:', err);
    }
  };

  // 加载所有分组配置 - 新增方法
  const loadAllGroups = async () => {
    setLoading(true);
    setError(null);
    try {
      console.log('🔄 正在加载所有分组配置...');
      const result = await plcService.loadAllGroups();
      if (result.success) {
        setGroups(result.groups.groups || []);
        // 初始化每个分组的变量列表
        const initialVariables = {};
        (result.groups.groups || []).forEach(group => {
          initialVariables[group.id] = group.variables.map(v => ({ 
            ...v, 
            value: '' 
          }));
        });
        setGroupVariables(initialVariables);
        saveGroupsToLocalStorage(result.groups.groups || []);
        showNotification(`✅ 成功加载 ${result.groups.groups.length} 个分组`, 'success');
        
        // 如果有分组，默认选择第一个
        if (result.groups.groups && result.groups.groups.length > 0) {
          setActiveGroup(result.groups.groups[0].id);
        }
      } else {
        const errorMessage = result.error || result.message || '未知错误';
        setError('加载分组配置失败: ' + errorMessage);
        alert('❌ 加载分组配置失败: ' + errorMessage);
      }
    } catch (err) {
      const errorMessage = err.message || '加载分组配置时发生未知错误';
      setError('加载分组配置失败: ' + errorMessage);
      alert('❌ 加载分组配置时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 加载指定分组配置 - 新增方法
  const loadGroup = async (groupId) => {
    setLoading(true);
    setError(null);
    try {
      console.log(`🔄 正在加载分组配置: ${groupId}`);
      const result = await plcService.loadGroup(groupId);
      if (result.success) {
        // 更新分组列表
        const updatedGroups = [...groups];
        const existingIndex = updatedGroups.findIndex(g => g.id === groupId);
        if (existingIndex >= 0) {
          updatedGroups[existingIndex] = result.group;
        } else {
          updatedGroups.push(result.group);
        }
        setGroups(updatedGroups);
        // 更新分组变量列表
        setGroupVariables(prev => ({
          ...prev,
          [groupId]: result.group.variables.map(v => ({ 
            ...v, 
            value: '' 
          }))
        }));
        saveGroupsToLocalStorage(updatedGroups);
        
        showNotification(`✅ 分组 ${groupId} 配置加载成功`, 'success');
      } else {
        const errorMessage = result.error || result.message || '未知错误';
        setError('加载分组配置失败: ' + errorMessage);
        alert('❌ 加载分组配置失败: ' + errorMessage);
      }
    } catch (err) {
      const errorMessage = err.message || '加载分组配置时发生未知错误';
      setError('加载分组配置失败: ' + errorMessage);
      alert('❌ 加载分组配置时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 清除本地存储的分组配置
  const clearStoredGroups = () => {
    localStorage.removeItem('plcGroups');
    setGroups([]);
    setGroupVariables({});
    setActiveGroup(null);
    showNotification('🗑️ 已清除本地存储的分组配置', 'info');
  };

  // 保存当前分组配置到文件
  const handleSaveGroupConfig = async () => {
    if (!activeGroup) {
      alert('❌ 请先选择一个分组');
      return;
    }
    
    setLoading(true);
    setError(null);
    try {
      // 获取当前分组的变量列表
      const currentVariables = groupVariables[activeGroup] || [];
      
      // 找到当前分组的配置
      const group = groups.find(g => g.id === activeGroup);
      if (!group) {
        throw new Error('未找到当前分组配置');
      }
      
      // 构造要保存的分组配置对象
      const groupConfigToSave = {
        ...group,
        variables: currentVariables.map(v => ({
          address: v.address,
          name: v.name || v.description || '',
          description: v.description || v.name || '',
          type: v.type || 'UNKNOWN'
        }))
      };
      
      // 保存分组配置
      const result = await plcService.saveGroupConfig(activeGroup, groupConfigToSave);
      
      if (result.success) {
        showNotification('✅ 分组配置保存成功', 'success');
        // 更新本地存储
        const updatedGroups = groups.map(g => 
          g.id === activeGroup ? {...g, variables: groupConfigToSave.variables} : g
        );
        setGroups(updatedGroups);
        saveGroupsToLocalStorage(updatedGroups);
      } else {
        throw new Error(result.message || '保存分组配置失败');
      }
    } catch (err) {
      const errorMessage = err.message || '保存分组配置时发生未知错误';
      setError('保存分组配置失败: ' + errorMessage);
      alert('❌ 保存分组配置时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 另存为分组配置文件
  const handleSaveAsGroupConfig = async () => {
    if (!activeGroup) {
      alert('❌ 请先选择一个分组');
      return;
    }
    
    // 弹出输入框让用户输入新的分组ID
    const newGroupId = prompt('请输入新的分组ID:', `${activeGroup}-copy`);
    if (!newGroupId) {
      return; // 用户取消操作
    }
    
    setLoading(true);
    setError(null);
    try {
      // 获取当前分组的变量列表
      const currentVariables = groupVariables[activeGroup] || [];
      
      // 找到当前分组的配置
      const group = groups.find(g => g.id === activeGroup);
      if (!group) {
        throw new Error('未找到当前分组配置');
      }
      
      // 构造要保存的分组配置对象
      const groupConfigToSave = {
        ...group,
        id: newGroupId,
        name: `${group.name} (副本)`,
        variables: currentVariables.map(v => ({
          address: v.address,
          name: v.name || v.description || '',
          description: v.description || v.name || '',
          type: v.type || 'UNKNOWN'
        }))
      };
      
      // 另存为分组配置
      const result = await plcService.saveAsGroupConfig(newGroupId, groupConfigToSave);
      
      if (result.success) {
        showNotification('✅ 分组配置另存为成功', 'success');
        // 重新加载分组文件列表
        await loadGroupFiles();
        // 如果当前分组列表中没有新分组，则添加它
        const updatedGroups = [...groups, groupConfigToSave];
        setGroups(updatedGroups);
        saveGroupsToLocalStorage(updatedGroups);
        // 设置新分组为活动分组
        setActiveGroup(newGroupId);
        // 初始化新分组的变量列表
        setGroupVariables(prev => ({
          ...prev,
          [newGroupId]: groupConfigToSave.variables.map(v => ({ ...v, value: '' }))
        }));
      } else {
        throw new Error(result.message || '另存为分组配置失败');
      }
    } catch (err) {
      const errorMessage = err.message || '另存为分组配置时发生未知错误';
      setError('另存为分组配置失败: ' + errorMessage);
      alert('❌ 另存为分组配置时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 删除分组配置文件
  const handleDeleteGroupConfig = async () => {
    if (!activeGroup) {
      alert('❌ 请先选择一个分组');
      return;
    }
    
    if (!confirm(`确认要删除分组配置 ${activeGroup} 吗？`)) {
      return; // 用户取消操作
    }
    
    setLoading(true);
    setError(null);
    try {
      console.log(`🔄 正在删除分组配置: ${activeGroup}`);
      const result = await plcService.deleteGroupConfig(activeGroup);
      if (result.success) {
        // 更新分组列表
        const updatedGroups = groups.filter(g => g.id !== activeGroup);
        setGroups(updatedGroups);
        // 更新分组变量列表
        setGroupVariables(prev => {
          const { [activeGroup]: _, ...rest } = prev;
          return rest;
        });
        saveGroupsToLocalStorage(updatedGroups);
        
        showNotification(`✅ 分组 ${activeGroup} 配置删除成功`, 'success');
        setActiveGroup(null);
      } else {
        const errorMessage = result.error || result.message || '未知错误';
        setError('删除分组配置失败: ' + errorMessage);
        alert('❌ 删除分组配置失败: ' + errorMessage);
      }
    } catch (err) {
      const errorMessage = err.message || '删除分组配置时发生未知错误';
      setError('删除分组配置失败: ' + errorMessage);
      alert('❌ 删除分组配置时发生错误: ' + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 添加变量到当前分组
  const addGroupVariable = () => {
    if (!activeGroup) return;
    
    const newVariables = [
      ...(groupVariables[activeGroup] || []),
      createDefaultVariable()
    ];
    
    setGroupVariables(prev => ({
      ...prev,
      [activeGroup]: newVariables
    }));
    
    console.log(`添加变量到分组 ${activeGroup} 后，当前变量状态:`, newVariables);
  };

  // 删除分组中的变量
  const removeGroupVariable = (index) => {
    if (!activeGroup) return;
    
    const currentVariables = groupVariables[activeGroup] || [];
    if (currentVariables.length <= 1) return;
    
    const newVariables = [...currentVariables];
    newVariables.splice(index, 1);
    
    setGroupVariables(prev => ({
      ...prev,
      [activeGroup]: newVariables
    }));
    
    console.log(`从分组 ${activeGroup} 删除变量后，当前变量状态:`, newVariables);
  };

  // 更新分组中的变量
  const updateGroupVariable = (index, field, value) => {
    if (!activeGroup) return;
    
    // 使用函数式更新确保获取到最新状态
    setGroupVariables(prev => {
      const currentVariables = prev[activeGroup] || [];
      const newVariables = [...currentVariables];
      
      // 确保索引有效
      if (index >= 0 && index < newVariables.length) {
        newVariables[index][field] = value;
        
        console.log(`更新分组 ${activeGroup} 变量[${index}].${field}后:`, {
          index,
          field,
          value,
          newVariables: JSON.stringify(newVariables, null, 2)
        });
        
        return {
          ...prev,
          [activeGroup]: newVariables
        };
      }
      
      console.log(`索引 ${index} 超出范围，当前变量数量: ${newVariables.length}`);
      return prev;
    });
  };

  // 设置三态选择框的值
  const handleGroupTriStateChange = (index, value) => {
    updateGroupVariable(index, 'value', value);
  };

  // 读取当前分组的变量
  const handleReadGroup = async () => {
    if (!activeGroup) {
      alert('❌ 请先选择一个分组');
      return;
    }
    
    setLoading(true);
    setError(null);
    try {
      console.log(`🔄 正在读取分组 ${activeGroup} 的变量...`);
      
      // 直接使用当前界面中的变量列表，而不是从配置文件重新加载
      const currentVariables = groupVariables[activeGroup] || [];
      
      const result = await handleRead(currentVariables, true, activeGroup);
      if (result.success) {
        // 确保获取正确的变量值数据
        const valuesData = result.values || result;
        
        // 更新界面中的变量值
        setGroupData(prev => ({
          ...prev,
          [activeGroup]: {
            data: valuesData
          }
        }));
        
        showNotification(`✅ 成功读取 ${Object.keys(valuesData).length} 个变量`, 'success');
      }
    } catch (err) {
      alert('❌ ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  // 写入分组中的变量
  const handleWriteGroupVariables = async () => {
    if (!activeGroup) {
      alert('❌ 请先选择一个分组');
      return;
    }
    
    try {
      const variables = groupVariables[activeGroup] || [];
      const result = await handleWrite(variables, true, activeGroup);
      
      if (result.failCount > 0) {
        // 显示失败的变量信息
        const failedMessages = result.failedVariables.map(v => 
          `❌ ${v.name} 失败: ${v.error}`
        ).join('\n');
        alert(`⚠️ 成功写入 ${result.successCount}/${result.total} 个变量，${result.failCount} 个失败\n\n${failedMessages}`);
      } else if (result.successCount > 0) {
        showNotification(`✅ 成功写入 ${result.successCount}/${result.total} 个变量`, 'success');
        // 重新读取该分组以更新显示
        await handleReadGroup();
      } else {
        showNotification('⚠️ 没有变量被成功写入', 'warning');
      }
    } catch (err) {
      alert('❌ ' + err.message);
    }
  };

  return (
    <div className="plc-panel">
      <h2>PLC分组控制面板</h2>
      
      {error && (
        <div className="error-message">
          <strong>错误:</strong> {error}
        </div>
      )}
      
      <div className="plc-controls">
        <button 
          onClick={handleConnect} 
          disabled={loading || isConnected}
          className={isConnected ? 'connected' : ''}
        >
          {loading ? '连接中...' : (isConnected ? '✅ 已连接' : '🔌 连接PLC')}
        </button>
        
        <button 
          onClick={handleDisconnect} 
          disabled={loading || !isConnected}
        >
          {loading ? '断开中...' : '🚫 断开PLC'}
        </button>
        
        <button 
          onClick={loadGroupFiles} 
          disabled={loading}
        >
          {loading ? '加载中...' : '🔄 刷新分组列表'}
        </button>
        
        <button 
          onClick={() => {
            if (activeGroup) {
              loadGroup(activeGroup);
            } else {
              alert('❌ 请先选择一个分组');
            }
          }} 
          disabled={loading || !activeGroup}
        >
          {loading ? '加载中...' : '📂 加载选中分组'}
        </button>
        
        <button 
          onClick={handleSaveGroupConfig} 
          disabled={loading || !activeGroup}
        >
          {loading ? '保存中...' : '💾 保存分组'}
        </button>
        
        <button 
          onClick={handleSaveAsGroupConfig} 
          disabled={loading || !activeGroup}
        >
          {loading ? '另存中...' : '💾 另存分组'}
        </button>
        
        <button 
          onClick={handleDeleteGroupConfig} 
          disabled={loading || !activeGroup}
        >
          {loading ? '删除中...' : '🗑️ 删除分组'}
        </button>
      </div>
      
      <div className="plc-groups">
        <h3>分组列表</h3>
        <div className="group-list-container">
          {/* 分组统计信息 */}
          <div className="group-stats">
            <span>共 {groups.length} 个分组</span>
            {activeGroup && (
              <span className="active-group-info">
                当前选中: {groups.find(g => g.id === activeGroup)?.name || activeGroup}
              </span>
            )}
          </div>
          
          {/* 分组搜索框 */}
          <div className="group-search">
            <input
              type="text"
              placeholder="搜索分组..."
              value={groupSearchTerm || ''}
              onChange={(e) => setGroupSearchTerm(e.target.value)}
              className="search-input"
            />
          </div>
          
          {/* 分组列表 */}
          <div className="group-list">
            {console.log('📊 当前分组数量:', groups.length)}
            {console.log('📊 当前分组列表:', groups)}
            {filteredGroups.map((group) => (
              <div
                key={group.id}
                className={`group-item ${activeGroup === group.id ? 'active' : ''}`}
                onClick={() => setActiveGroup(group.id)}
              >
                <div className="group-header">
                  <span className="group-name">{group.name}</span>
                  {activeGroup === group.id && (
                    <span className="group-active-indicator">✓</span>
                  )}
                </div>
                <div className="group-details">
                  <span className="group-id">ID: {group.id}</span>
                  <span className="group-variable-count">
                    变量数: {(group.variables || []).length}
                  </span>
                </div>
                {group.description && (
                  <div className="group-description">
                    {group.description}
                  </div>
                )}
              </div>
            ))}
          </div>
          
          {/* 如果没有分组，显示提示信息 */}
          {groups.length === 0 && (
            <div className="no-groups-message">
              <p>暂无分组配置</p>
              <button onClick={loadGroupFiles} disabled={loading}>
                {loading ? '加载中...' : '🔄 刷新分组列表'}
              </button>
            </div>
          )}
        </div>
        
        {console.log('📊 groupFiles状态:', groupFiles)}
        {console.log('📊 groups状态:', groups)}
        
        {activeGroup && (
          <div className="group-variables">
            {/* 显示当前分组的详细信息 */}
            <div className="active-group-details">
              <h3>
                分组变量配置 - {groups.find(g => g.id === activeGroup)?.name || activeGroup}
              </h3>
              <div className="group-info-tags">
                <span className="info-tag">
                  <strong>ID:</strong> {activeGroup}
                </span>
                <span className="info-tag">
                  <strong>变量数:</strong> {(groupVariables[activeGroup] || []).length}
                </span>
                {groups.find(g => g.id === activeGroup)?.description && (
                  <span className="info-tag">
                    <strong>描述:</strong> {groups.find(g => g.id === activeGroup)?.description}
                  </span>
                )}
              </div>
            </div>
            
            <table className="variables-table">
              <thead>
                <tr>
                  <th>变量名</th>
                  <th>变量地址</th>
                  <th>设置值</th>
                  <th>读取值(快照)</th>
                  <th>类型/操作</th>
                </tr>
              </thead>
              <tbody>
                {console.log('📊 渲染变量列表:', groupVariables[activeGroup])}
                {(groupVariables[activeGroup] || []).map((variable, index) => (
                  <PLCVariableRow
                    key={index}
                    variable={variable}
                    index={index}
                    onUpdate={updateGroupVariable}
                    onRemove={removeGroupVariable}
                    onTriStateChange={handleGroupTriStateChange}
                    showReadValue={true}
                    groupData={groupData}
                    groupId={activeGroup}
                    isGroup={true}
                    totalVariables={(groupVariables[activeGroup] || []).length}
                  />
                ))}
              </tbody>
            </table>
            
            <button onClick={addGroupVariable} className="add-variable-btn">
              ➕ 添加变量
            </button>
          </div>
        )}
      </div>
      
      <div className="plc-actions">
        <button onClick={handleReadGroup} disabled={loading || !isConnected || !activeGroup}>
          {loading ? '读取中...' : '📥 读取分组变量'}
        </button>
        
        <button onClick={handleWriteGroupVariables} disabled={loading || !isConnected || !activeGroup}>
          {loading ? '写入中...' : '📤 写入分组变量'}
        </button>
      </div>
    </div>
  );
}